import {_decorator, CCInteger, Component, EventKeyboard, input, Input, KeyCode, v3} from 'cc';

const {ccclass, property} = _decorator;

@ccclass('PlayerController')
export class PlayerController extends Component {
    /**
     * 移动速度
     */
    @property(CCInteger)
    speed: number = 100;
    /**
     * 当前按键
     */
    private keyCode: KeyCode = null;
    /**
     * 键集
     */
    private keys: KeyCode[] = [];

    start() {
        // 键盘事件
        input.on(Input.EventType.KEY_DOWN, (event: EventKeyboard) => {
            // 存入最新按键
            this.keys.push(event.keyCode);
            // 获取最新按键
            this.keyCode = this.keys[this.keys.length - 1];
        });
        input.on(Input.EventType.KEY_UP, (event: EventKeyboard) => {
            // 移除抬起的按键
            this.keys.splice(this.keys.findIndex((value) => {
                return value === event.keyCode;
            }), 1);
            // 当无按键时
            if (this.keys.length === 0) {
                // 按键置空
                this.keyCode = null;
            } else {
                // 获取最新按键
                this.keyCode = this.keys[this.keys.length - 1];
            }
        });
    }

    update(deltaTime: number) {
        if (this.keyCode) {
            switch (this.keyCode) {
                case KeyCode.KEY_W:
                    this.node.setPosition(v3(this.node.position.x, this.node.position.y + this.speed * deltaTime));
                    break;
                case KeyCode.KEY_S:
                    this.node.setPosition(v3(this.node.position.x, this.node.position.y - this.speed * deltaTime));
                    break;
                case KeyCode.KEY_A:
                    this.node.setPosition(v3(this.node.position.x - this.speed * deltaTime, this.node.position.y));
                    break;
                case KeyCode.KEY_D:
                    this.node.setPosition(v3(this.node.position.x + this.speed * deltaTime, this.node.position.y));
                    break;
            }
        }
    }
}

